package com.rtsapp.server.platform.hm;

import com.rtsapp.server.app.AppConfig;
import com.rtsapp.server.platform.IPlatformLoginService;
import com.rtsapp.server.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import com.rtsapp.server.logger.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by admin on 16-2-24.
 */
public class HMLoginService implements IPlatformLoginService {

    private static final Logger LOGGER = com.rtsapp.server.logger.LoggerFactory.getLogger( HMLoginService.class );

    /**
     * SDK服务器登录验证URL
     * http://api.haimawan.com/index.php?m=api&a=validate_token
     */
    private static final String POST_URL = AppConfig.getInstance().getHMUrl();
    /**
     * 应用的APP ID
     * 6326bcaf0f3bb7d2e7f47211e864798c
     */
    private static final String APP_ID = AppConfig.getInstance().getHMAppId();

    //    15b7d0fd9ad986b11f25a3ff76acf375
    private static final String APP_KEY = AppConfig.getInstance().getHMAppKey();


    @Override
    public String  validateLoginToken(String token, String uid ) {

        LOGGER.info( "海马SDK登陆:token="+token + ",uid=" + uid );

        try {

            String result = checkSession( token, APP_ID, uid );
            LOGGER.info( "海马SDK登陆验证返回:" + result );

            if( ! StringUtils.isEmpty( result) ){

                if( result.startsWith( "success&" ) ){
                    String resultUID = result.substring( "success&".length() );

                    LOGGER.info( "海马SDK登陆成功:uid=" + resultUID );

                    return "hm_" + resultUID;
                }
            }
        } catch (IOException e) {
            LOGGER.error( "海马SDK 用户验证调用异常", e );
            return null;
        }

        return null;
    }

    public static String checkSession( String token, String appId, String uid ) throws IOException
    {
        if (null == token || null == appId || null == uid)
        {
            return null;
        }

        String content = "appid="+appId+"&t="+token+"&uid="+uid;

        return httpPost(POST_URL, content);
    }


    /**
     * http post json string
     * @param url
     * @param content
     * @return
     * @throws IOException
     */
    public static String httpPost(String url, String content) throws IOException
    {
        if (null == url || url.isEmpty() || null == content || content.isEmpty())
        {
            return "";
        }
        // 请求地址
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        // 设置超时时间为3s
        RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setAuthenticationEnabled(false).build();
        httpPost.setConfig(config);

        // 设置参数
        StringEntity se = new StringEntity(content);
        httpPost.setEntity(se);

        // 准备环境
        try (CloseableHttpClient http = HttpClients.createDefault(); CloseableHttpResponse response = http.execute(httpPost);)
        {
            // 返回内容
            HttpEntity entity = response.getEntity();
            // 主体数据
            InputStream in = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            // 读取
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            return sb.toString();
        }
    }


}
